package com.limeng.server;

import com.limeng.catalina.mapper.MappedHost;
import com.limeng.catalina.mapper.MappedWrapper;
import com.limeng.catalina.mapper.Mapper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Set;

public class MiniServerThread implements Runnable {

    private Socket socket;

    private Mapper mapper;

    public MiniServerThread(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            String path = request.getUrl();
            OutputStream outputStream = socket.getOutputStream();
            Response response = new Response(outputStream);

//            MappedHost host = mapper.getHost();
            String contextName = "";
            Set<String> contextNames = mapper.getContextNames();
            for (String context: contextNames) {
                if(path.contains(context)){
                    contextName = context;
                    break;
                }
            }
//            System.out.println(path);
            String url = path.substring(("/"+contextName).length());
            System.out.println(url);
            MappedWrapper wrapper = mapper.getWrapper(contextName, url);
            if(wrapper!=null){
                Servlet servlet = wrapper.getServlet();
                servlet.service(request, response);
            }else{
                response.writeHtml(request.getUrl());
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
